import { JSONParse, JSONStringify } from 'wft-utils'

class StorageCache {
  #storage: Storage
  constructor(isLocal = true) {
    this.#storage = isLocal ? window.localStorage : window.sessionStorage
  }

  setCache(key: string, value: any) {
    const dataType = typeof value
    const dateTime = new Date().getTime()
    const obj = { value, dataType, dateTime }
    this.#storage.setItem(key, JSONStringify(obj))
  }

  getCache(key: string) {
    const result = this.#storage.getItem(key)
    return result ? JSONParse(result).value : result
  }

  getAllCache() {
    const list = []
    for (let i = 0; i < this.#storage.length; i++) {
      const curKey = this.#storage.key(i) as string
      list.push({
        key: curKey,
        value: this.getCache(curKey)
      })
    }
    return list
  }

  removeCache(key: string) {
    this.#storage.removeItem(key)
  }

  clear() {
    this.#storage.clear()
  }
}

export const localCache = new StorageCache(true)
export const sessionCache = new StorageCache(false)